package com.example.demo.listener;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class FanoutListener {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = "product1.queue")
    public void product1(Message message, Channel channel) throws IOException {
        System.out.println(new String(message.getBody()));
        // 消息丢弃，进入死信队列
        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        rabbitTemplate.send("dlx.queue",message);
    }

    @RabbitListener(queues = "product2.queue")
    public void product2(Message message,Channel channel) throws IOException {
        System.out.println(new String(message.getBody()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "dlx.queue"),
                    exchange = @Exchange(value = "dlx.exchange"),
                    key = "#"
            )
    })
    public void receive2(Message message, Channel channel) throws IOException {
        System.out.println("我是一条死信:"+message);
        byte[] body = message.getBody();
        String str = new String(body,"UTF-8");
        System.out.println("死信消息 ： " + str );
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,true);
    }
}
